package cn.jbolt.common.service;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.annotation.Target;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.print.Doc;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.codec.Base64.InputStream;

import cn.jbolt.common.model.Wlxx;

public class PdfService {
	public static void createQrCodePdf(String[] codeArr,String wlh) throws IOException, DocumentException { // 根据模板生成PDF
		Wlxx wlxx=Wlxx.dao.findById(wlh);
		List<String> fileList=new ArrayList();
		for (int i = 0; i < codeArr.length; i++) {
			String templatePath = "C:/download/barpdf/templatePdf/xlyTemplate.pdf"; // 模板路径
			String newPdfPath = "C:/download/barpdf/tmpPdf/"+codeArr[i]+".pdf"; // 生成新文件的路径
			fileList.add(newPdfPath);
			String fieldName="bar";	//书签名
			String imgPathQrCode="C:/download/barpdf/tmpImg/"+codeArr[i]+".png";	//二维码图片路径
			String imgPathBarCode="C:/download/barpdf/tmpImg/"+codeArr[i]+".png";	//条形码图片路径
			FileOutputStream out;
			PdfReader reader;
			ByteArrayOutputStream bos;
			PdfStamper stamper;
			out=new FileOutputStream(newPdfPath);
			reader=new PdfReader(templatePath);
			bos=new ByteArrayOutputStream();
			stamper=new PdfStamper(reader, bos);
			AcroFields form=stamper.getAcroFields();
			Map map=new HashMap<String, String>();
			form.setField("wlms1", wlxx.get("wlms1"));
			form.setField("wlms2", wlxx.get("wlms2"));
			form.setField("rq", codeArr[i].substring(0, 2)+"."+codeArr[i].substring(2, 4)+"."+codeArr[i].substring(4, 6));
			form.setField("sj", codeArr[i].substring(6, 8)+":"+codeArr[i].substring(8, 10)+":"+codeArr[i].substring(10, 12));
			int pageNo=form.getFieldPositions(fieldName).get(0).page;
			Rectangle singRect=form.getFieldPositions(fieldName).get(0).position;
			float x=singRect.getLeft();
			float y=singRect.getBottom();
			//读图片
			Image imageQrCode=Image.getInstance(imgPathQrCode);
			Image imgBarCode=Image.getInstance(imgPathBarCode);
			//获取操作界面
			PdfContentByte under=stamper.getOverContent(pageNo);
			//根据域的大小缩放图片
			imageQrCode.scaleToFit(singRect.getWidth(),singRect.getHeight());
			imgBarCode.scaleToFit(singRect.getWidth(),singRect.getHeight());
			//添加图片
			imageQrCode.setAbsolutePosition(x, y);
			imgBarCode.setAbsolutePosition(x, y);
			under.addImage(imageQrCode);
//			under.addImage(imgBarCode);
			stamper.setFormFlattening(true);	
			stamper.close();
			Document doc = new Document();
            PdfCopy copy = new PdfCopy(doc, out);
            doc.open();
            PdfImportedPage importPage = copy.getImportedPage(
                    new PdfReader(bos.toByteArray()), 1);
            copy.addPage(importPage);
            doc.close();
            reader.close();
		}
		Document document = null;
        try {
            document = new Document(new PdfReader(fileList.get(0)).getPageSize(1));
            PdfCopy copy = new PdfCopy(document, new FileOutputStream("C:/download/barpdf/pdf/"+codeArr[1]+".pdf"));
            document.open();
            for (int i = 0; i < fileList.size(); i++) {
                PdfReader reader = new PdfReader(fileList.get(i));
                int n = reader.getNumberOfPages();// 获得总页码
                for (int j = 1; j <= n; j++) {
                    document.newPage();
                    PdfImportedPage page = copy.getImportedPage(reader, j);// 从当前Pdf,获取第j页
                    copy.addPage(page);
                }
                reader.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        } finally {
            if (document != null) {
                document.close();
            }
            System.out.println("finish " + new Date());
        }
	}
	
	public static void createQrCodePdf3(String[] codeArr,String wlh) throws IOException, DocumentException { // 根据模板生成PDF
		Wlxx wlxx=Wlxx.dao.findById(wlh);
		List<String> fileList=new ArrayList();
		for (int i = 0; i < codeArr.length; i=i+3) {
			String templatePath = "C:/download/barpdf/templatePdf/xlyTemplate3.pdf"; // 模板路径
			String newPdfPath = "C:/download/barpdf/tmpPdf/xly"+codeArr[i]+".pdf"; // 生成新文件的路径
			fileList.add(newPdfPath);
			
			//第一张生产码
			String fieldName1="bar1-1";	//书签名
			String imgPath1="C:/download/barpdf/tmpImg/"+codeArr[i]+".png";	//图片路径
			//第二张生产码
			String fieldName2="bar1-2";	//书签名
			String imgPath2="C:/download/barpdf/tmpImg/"+codeArr[i+1]+".png";	//图片路径
			//第三张生产码
			String fieldName3="bar1-3";	//书签名
			String imgPath3="C:/download/barpdf/tmpImg/"+codeArr[i+2]+".png";	//图片路径
			FileOutputStream out;
			PdfReader reader;
			ByteArrayOutputStream bos;
			PdfStamper stamper;
			out=new FileOutputStream(newPdfPath);
			reader=new PdfReader(templatePath);
			bos=new ByteArrayOutputStream();
			stamper=new PdfStamper(reader, bos);
			AcroFields form=stamper.getAcroFields();
			Map map=new HashMap<String, String>();
			//第一张
			form.setField("wlms1-1", wlxx.get("wlms1"));
			form.setField("wlms2-1", wlxx.get("wlms2"));
			form.setField("rq1-1", codeArr[i].substring(0, 2)+"."+codeArr[i].substring(2, 4)+"."+codeArr[i].substring(4, 6));
			form.setField("sj1-1", codeArr[i].substring(6, 8)+":"+codeArr[i].substring(8, 10)+":"+codeArr[i].substring(10, 12));
			//第二张
			form.setField("wlms1-2", wlxx.get("wlms1"));
			form.setField("wlms2-2", wlxx.get("wlms2"));
			form.setField("rq1-2", codeArr[i+1].substring(0, 2)+"."+codeArr[i+1].substring(2, 4)+"."+codeArr[i+1].substring(4, 6));
			form.setField("sj1-2", codeArr[i+1].substring(6, 8)+":"+codeArr[i+1].substring(8, 10)+":"+codeArr[i+1].substring(10, 12));
			//第三张
			form.setField("wlms1-3", wlxx.get("wlms1"));
			form.setField("wlms2-3", wlxx.get("wlms2"));
			form.setField("rq1-3", codeArr[i+2].substring(0, 2)+"."+codeArr[i+2].substring(2, 4)+"."+codeArr[i+2].substring(4, 6));
			form.setField("sj1-3", codeArr[i+2].substring(6, 8)+":"+codeArr[i+2].substring(8, 10)+":"+codeArr[i+2].substring(10, 12));
			
			int pageNo1=form.getFieldPositions(fieldName1).get(0).page;
			Rectangle singRect1=form.getFieldPositions(fieldName1).get(0).position;
			float x=singRect1.getLeft();
			float y=singRect1.getBottom();
			//读图片
			Image image1=Image.getInstance(imgPath1);
			//获取操作界面
			PdfContentByte under1=stamper.getOverContent(pageNo1);
			//根据域的大小缩放图片
			image1.scaleToFit(singRect1.getWidth(),singRect1.getHeight());
			//添加图片
			image1.setAbsolutePosition(x, y);
			under1.addImage(image1);
			
			int pageNo2=form.getFieldPositions(fieldName2).get(0).page;
			Rectangle singRect2=form.getFieldPositions(fieldName2).get(0).position;
			x=singRect2.getLeft();
			y=singRect2.getBottom();
			//读图片
			Image image2=Image.getInstance(imgPath2);
			//获取操作界面
			PdfContentByte under2=stamper.getOverContent(pageNo2);
			//根据域的大小缩放图片
			image2.scaleToFit(singRect2.getWidth(),singRect2.getHeight());
			//添加图片
			image2.setAbsolutePosition(x, y);
			under2.addImage(image2);
			
			int pageNo3=form.getFieldPositions(fieldName3).get(0).page;
			Rectangle singRect3=form.getFieldPositions(fieldName3).get(0).position;
			x=singRect3.getLeft();
			y=singRect3.getBottom();
			//读图片
			Image image3=Image.getInstance(imgPath3);
			//获取操作界面
			PdfContentByte under3=stamper.getOverContent(pageNo3);
			//根据域的大小缩放图片
			image3.scaleToFit(singRect3.getWidth(),singRect3.getHeight());
			//添加图片
			image3.setAbsolutePosition(x, y);
			under3.addImage(image3);
			stamper.setFormFlattening(true);	
			stamper.close();
			Document doc = new Document();
            PdfCopy copy = new PdfCopy(doc, out);
            doc.open();
            PdfImportedPage importPage = copy.getImportedPage(
                    new PdfReader(bos.toByteArray()), 1);
            copy.addPage(importPage);
            doc.close();
            reader.close();
		}
		Document document = null;
        try {
            document = new Document(new PdfReader(fileList.get(0)).getPageSize(1));
            PdfCopy copy = new PdfCopy(document, new FileOutputStream("C:/download/barpdf/pdf/"+codeArr[1]+".pdf"));
            document.open();
            for (int i = 0; i < fileList.size(); i++) {
                PdfReader reader = new PdfReader(fileList.get(i));
                int n = reader.getNumberOfPages();// 获得总页码
                for (int j = 1; j <= n; j++) {
                    document.newPage();
                    PdfImportedPage page = copy.getImportedPage(reader, j);// 从当前Pdf,获取第j页
                    copy.addPage(page);
                }
                reader.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        } finally {
            if (document != null) {
                document.close();
            }
            System.out.println("finish " + new Date());
        }
	}
	
    public static String[] getFiles() {
        String filepath="C:/download/barpdf/xly";
        File file=new File(filepath);
        File[] filesTmp = file.listFiles();
        String[] files=new String[filesTmp.length];
        for (int i = 0; i < filesTmp.length; i++) {
        	files[i]=filesTmp[i].getPath();
		}
        return files;
    }
    public static void mergePdfFiles(String[] files) throws IOException, DocumentException{
    	Document document=new Document(new PdfReader(files[0]).getPageSize(1));
    	PdfCopy copy=new PdfCopy(document, new FileOutputStream("C:/download/barpdf/xly.pdf"));
    	document.open();
    	for (int i = 0; i < files.length; i++) {
			PdfReader reader=new PdfReader(files[i]);
			int n=reader.getNumberOfPages();
			for (int j = 0; j <=n; j++) {
				document.newPage();
				PdfImportedPage page=copy.getImportedPage(reader, j);
				copy.addPage(page);
			}
		}
    	document.close();
    }
}